﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;


namespace Hyt.Core.Data
{
    public abstract class ValidModel : IValidModel
    {
        protected readonly List<ValidError> ValidErrors = new List<ValidError>();

        private bool _modelIsValid = true;
        protected bool ModelIsValid
        {
            get { return _modelIsValid; }
            set { _modelIsValid = value; }
        }

        public virtual void Valid()
        {
            ValidErrors.Clear();
            Type t = this.GetType();
            var descriptor = new AssociatedMetadataTypeTypeDescriptionProvider(t).GetTypeDescriptor(t);

            foreach (PropertyDescriptor propertyDescriptor in descriptor.GetProperties())
            {
                foreach (var validationAttribute in propertyDescriptor.Attributes.OfType<ValidationAttribute>())
                {
                    if (!validationAttribute.IsValid(propertyDescriptor.GetValue(this)))
                    {
                        ValidError ve = new ValidError();
                        ve.Property = propertyDescriptor.Name;
                        ve.Message = validationAttribute.FormatErrorMessage(propertyDescriptor.Name);
                        ValidErrors.Add(ve);
                    }
                }
            }
        }

        public virtual bool IsValid()
        {
            Valid();
            return ModelIsValid;
        }

        public virtual string GetErrorSummary(string joinstr)
        {
            return String.Join(joinstr, ValidErrors.Select(t => t.Message));
        }

        public virtual List<ValidError> GetVerboseError()
        {
            return ValidErrors;
        }

    }
}
